<template>
  <view class="answer-page" :class="fontClass">
    <QuestionHeader
      :current-question="currentQuestion"
      :question-data="questionData"
      :show-setting-modal="showSettingModal"
      :show-feedback="showFeedback"
      :autoNextEnabled="autoNextEnabled"
      :request-handler="handleRequest"
      @update:showSettingModal="showSettingModal = $event"
      @update:showFeedback="showFeedback = $event"
      @set-font-size="setFontClass" 
      @update:autoNextEnabled="onAutoNextChange"
    />

    <QuestionContent
      :question-data="questionData"
      :selected-option="selectedOption"
      :is-correct="isCorrect"
      :show-analysis-content="showAnalysisContent"
      :answer-text="answerText"
      @update:selectedOption="selectedOption = $event"
      @onClick:Option="onClickOption"
    />
    <!-- 确认按钮 -->
    <BottomNav
      :show-card-modal="showCardModal"
      :current-question="currentQuestion"
      :question-list="questionList"
      :isCollected="isCollected"
      :AnalyseOrSubmit = "AnalyseOrSubmit"
      :answer-record-list="answerRecordList"
      :is-question-correct="isQuestionCorrect"
      :is-question-answered="isQuestionAnswered"
      @update:showCardModal="showCardModal = $event"
      @update:showAnalysis="showAnalysis"
      @prevQuestion="prevQuestion"
      @nextQuestion="nextQuestion"
      @goToQuestion="goToQuestion"
      @toggleCollect="toggleCollect"
    />
  </view>
</template>

<script setup>
import { ref, computed, onMounted,onUnmounted } from 'vue'
import QuestionHeader from '../../components/questionHeader.vue'
import QuestionContent from '../../components/questionContent.vue'
import BottomNav from '../../components/bottomNav.vue'
import Taro from '@tarojs/taro'
import config from '../../config'
//禁用标记，当选出正确答案，禁用选项(未启用)
const disableFlag = ref(false)
//禁用点击事件的标记
const readOnly = ref(true)
//问题集合列表
const questionList = ref([])
//当前问题索引
const currentQuestion = ref(0)
//选项集合
const selectedOption = ref([])
//判断答案是否正确标识(用于题目背景颜色)
const isCorrect = ref(null)
//题目解析控制器(背题模式专用true)
const showAnalysisContent = ref(true)
//设置弹窗是否显示
const showSettingModal = ref(false)
//反馈弹窗是否显示
const showFeedback = ref(false)
//答题卡(卡片)弹窗是否显示
const showCardModal = ref(false)
// 获取页面参数
const query = ref('')
const AnalyseOrSubmit = ref(true);
const autoNextEnabled = ref(false) // 默认不开启自动跳转
//当前问题对象
const questionData = ref({
  id: null,
  type: 1, // 题型：1-单选 2-多选 3-判断
  title: '',
  options: [], // 解析后的选项
  correctAnswer: '',
  analysis: ''
})
//用户答题记录需返回到后端的样式
const record =ref({
    userId : null,
    questionId: null,
    userAnswer: '',
    correct: null,
    updateTime: ''
  }) 
//用于答题记录集合
const answerRecordList = ref([])
//收藏对象
const collectData = ref({
  userId: null,
  questionId: null,
  createTime: '',
  delFlag: null
});
//收藏集合（）
const collectList = ref([]);
//已答题集合(未启用)
// const answeredQuestions = ref(Array(questionList.value.length).fill(false))
// 是否收藏
const isCollected = ref(false)
// 当前题目数据
// const currentQuestionData = computed(() => questionList.value[currentQuestion.value] || {})
const userId = ref(null);
//页面加载时获取题目列表(随机刷题不需要页面携带数据)
onMounted(() => {
  userId.value = Taro.getStorageSync('id');
  if (userId.value == null) {
    return Taro.navigateTo({
      url: '/pages/profile/index'
    })
  }
  fetchQuestions();
  // 进入页面后立即显示答案和解析(背题专属)
  showAnalysisContent.value = true
})
// 获取题目数据
const fetchQuestions = async () => {
  try {
    const wxRequest = config.wxPromisify(wx.request)
    const res = await wxRequest({
      url: `${config.apiUrl}/question/findAll`,
      method: 'GET',
      header: { 'content-type': 'application/json' }
    })
    //获取收藏列表
    const resCllotion = await wxRequest({
      url: `${config.apiUrl}/collection/find/${userId.value}`,
      method: 'GET',
      header: { 'content-type': 'application/json' }
    })

    console.log('接口返回:', res.data)

    if (res.data.code === '0') {
      questionList.value = res.data.data || []
      collectList.value = resCllotion.data.data || []
      updateQuestionData()
      isQuestionCollected(questionData.value.id)
      //(会导致保存时存在.数组初始化,但内容都是空值)(背题模式题目太多,不用初始化)
      // answerRecordList.value = Array(questionList.value.length).fill().map(() => (record));
    } else {
      Taro.showToast({ title: '获取题目失败', icon: 'none' })
    }

  } catch (err) {
    console.error('请求失败:', err)
    Taro.showToast({ title: '网络错误', icon: 'none' })
  }
}
//表格的点击事件
const onClickOption = (val) => {
  if (readOnly) return // 如果是只读模式，不响应点击
  console.log('点击了选项:', val)
  isCorrect.value = '0'
  if (questionData.value.type === 2) {
    // 多选题：确保是数组
    const arr = selectedOption.value || []

    const index = arr.indexOf(val)
    if (index > -1) {
      // 已存在则移除
      selectedOption.value = arr.filter(item => item !== val)
    } else {
      // 不存在则添加
      selectedOption.value = [...arr, val]
    }
  } else {
    // 单选/判断题
    selectedOption.value = val
  }
}
// 判断是否正确
const isQuestionCorrect = (index) => {
  const questionId = questionList.value[index]?.id;
  const existingIndex = answerRecordList.value.findIndex(r => r.questionId === questionId);
  if (existingIndex === -1) {
    return 2;
  }
  const q = answerRecordList.value[existingIndex]?.correct
  return q

  // const correct = formatCorrectAnswer(q.correctAnswer)
  // const user = formatCorrectAnswer(q.userAnswer)
}
// 判断是否已答题(答题卡弹窗)
const isQuestionAnswered = (index) => {
  const questionId = questionList.value[index]?.id;
  const existingIndex = answerRecordList.value.findIndex(r => r.questionId === questionId);
  if (existingIndex === -1) {
    return false;
  }
  const q = answerRecordList.value[existingIndex]?.correct
  return q !== 2
}
//判断是否收藏
function isQuestionCollected(questionId) {
  console.log('判断是否收藏id', questionId);
  const existingIndex = collectList.value.findIndex(item => item.questionId === questionId);
  if(existingIndex > -1){
    
  }
  isCollected.value = (existingIndex > -1);
  console.log('判断是否收藏', isCollected.value);
}
// 回答答案文字
const answerText = computed(() => {
  const ans = questionData.value.correctAnswer
  if (typeof ans === 'string') return ans
  if (Array.isArray(ans)) return ans.join(', ')
  return ''
})
// 格式化时间为 "YYYY-MM-DD HH:mm"
const formatTime = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从 0 开始
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}`
}
// 将正确答案统一转为字符串格式（如 ["A","B"] → "AB"）
const formatCorrectAnswer = (answer) => {
  if (!answer) return ''
  if (Array.isArray(answer)) {
    // 如果是数组，去重后排序并拼接成字符串
    return [...new Set(answer)].sort().join('')
  } else if (typeof answer === 'string') {
    // 如果是字符串，去除非字母字符后排序
    return answer.replace(/[^A-Z]/g, '').split('').sort().join('')
  }

  return ''
}
// 更新当前题目数据
const updateQuestionData = () => {
  if (questionList.value.length === 0) return

  const current = questionList.value[currentQuestion.value]

  // 查找答题记录
  const record = answerRecordList.value.find(r => r.questionId === current.id)

  questionData.value = {
    id: current.id,
    type: current.type,
    title: current.questionText,
    options: JSON.parse(current.answerOptions),
    correctAnswer: formatCorrectAnswer(current.correctAnswer),
    analysis: current.answerAnalysis,
    userAnswer: record ? record.userAnswer : null
  }

  // 根据题型初始化 selectedOption
  if (current.type === 2) {
    // 多选题
    selectedOption.value = record && record.userAnswer ? [...record.userAnswer] : []
  } else {
    // 单选/判断题
    selectedOption.value = record ? record.userAnswer : ''
  }

  // 设置是否正确状态
 // 如果已答过题，则使用历史答案；否则默认展示正确答案
  if (record && record.correct !== undefined) {
    isCorrect.value = record.correct === 1 ? '1' : '-1'
    selectedOption.value = formatAnswerForSave(record.userAnswer)
  } else {
    isCorrect.value = '1' // 直接标记为正确
    selectedOption.value = questionData.value.correctAnswer
  }
  showAnalysisContent.value = true // 每次切换都显示解析
}
// 收藏切换
const toggleCollect = () => {
  isCollected.value = !isCollected.value
  let questionId = questionData.value.id;
  if (isCollected.value) {
    // 收藏
    collectData.value = {
      userId: userId.value,
      questionId: questionId,
      createTime: formatTime(new Date()),
      delFlag: 0
    }
    collectList.value.push(collectData.value)
  } else {
    // 取消收藏
    const index = collectList.value.findIndex(item => item.questionId === questionId)
    if (index > -1) {
      collectList.value[index].delFlag = 1
    }
  }
  console.log('收藏列表', collectList.value)
  Taro.showToast({
    title: isCollected.value ? '已收藏' : '已取消收藏',
    icon: 'none'
  })

}
// 自动跳转开关变化
const onAutoNextChange = (val) => {
  autoNextEnabled.value = val
}
// 格式化答案为字符串存储（数组 → 字符串）
const formatAnswerForSave = (answer) => {
  if (!answer) return ''
  if (Array.isArray(answer)) {
    return answer.join('')
  }
  return answer
}
//保存答题记录
const saveAnswerRecord = (status) => {
  const current = questionList.value[currentQuestion.value]
  // const userId = Taro.getStorageSync('userId') || 1 // 示例：从本地缓存获取用户ID
  const questionId = current.id
  const userAnswer = selectedOption.value
  let correct = 2 // 默认为无答案
  console.log("提交答案", isCorrect.value)
  if (status === 'submit') {
    if (isCorrect.value === '1') {
      console.log('提交答案1');
      correct = 1
    } else if (isCorrect.value === '-1') {
      console.log('提交答案-1');
      correct = 0
    }
  }
  const record = {
    userId: userId.value,
    questionId,
    userAnswer: formatAnswerForSave(userAnswer),
    correct,
    updateTime: formatTime(new Date())
  }
  // 更新或新增记录
  const existingIndex = answerRecordList.value.findIndex(r => r.questionId === questionId)
  if (existingIndex > -1) {
    // 已存在则更新
    answerRecordList.value.splice(existingIndex, 1, record)
  } else {
    // 否则添加
    answerRecordList.value.push(record)
  }
}
// 答题方法
const confirmAnswer = () => {
  const correct = questionData.value.correctAnswer
  const userAnswer = selectedOption.value

  if (questionData.value.type === 2) {
    // 多选题：排序后转字符串比对
    const correctArray = correct.split(',').filter(Boolean)
    const userArray = selectedOption.value || []

    const correctSorted = correctArray.sort().join('')
    const userSorted = userArray.sort().join('')
    console.log('用户答案排序后:', userSorted);
    console.log('正确答案排序后:', correctSorted);
    if (userSorted === correctSorted) {
      isCorrect.value = '1'
      disableFlag.value = true
      Taro.showToast({ title: '回答正确!', icon: 'success' })
    } else {
      isCorrect.value = '-1'
      Taro.showToast({ title: '回答错误!', icon: 'none' })
    }
  } else {
    // 单选或判断题
    if (userAnswer === correct) {
      isCorrect.value = '1'
      disableFlag.value = true
      Taro.showToast({ title: '回答正确!', icon: 'success' })
    } else {
      isCorrect.value = '-1'
      Taro.showToast({ title: '回答错误!', icon: 'none' })
    }
  }

  // 提交后保存记录
  saveAnswerRecord('submit');
  // 如果启用自动跳转且不是最后一题
  if (autoNextEnabled.value && currentQuestion.value < questionList.value.length - 1) {
    setTimeout(() => {
      nextQuestion()
    }, 500)
  }
}
// 显示解析
const showAnalysis = () => {
  //用于答案的处理，使点击解析时，能出现答案
  answerText.value = formatCorrectAnswer(questionData.value.correctAnswer);
  showAnalysisContent.value = !showAnalysisContent.value
}
//将封装的请求发给子组件方法
const handleRequest = () =>{
   return config.wxPromisify(wx.request);
}
const prevQuestion = () => {
  if (currentQuestion.value > 0) {
    currentQuestion.value--
    resetQuestionState()
  }
}
// 提交所有记录到后端
const submitAllRecords = async () => {
  try {
    const wxRequest = config.wxPromisify(wx.request)
    console.log('answerRecordList', answerRecordList.value)
    const res = await wxRequest({
      url: `${config.apiUrl}/userAnswer/addAll`,
      method: 'POST',
      header: { 'content-type': 'application/json' },
      data: answerRecordList.value
    })
    const resCllotion = await wxRequest({
      url: `${config.apiUrl}/collection/save`,
      method: 'POST',
      header: { 'content-type': 'application/json' },
      data: collectList.value
    })
    if (res.data.code === '0' && resCllotion.data.code === '0') {
      Taro.showToast({ title: res.data.msg, icon: 'success' })
    } else {
      Taro.showToast({ title: res.data.msg, icon: 'none' })
    }
  } catch (err) {
    console.error('提交失败:', err)
    Taro.showToast({ title: '网络错误', icon: 'none' })
  }
}
const nextQuestion = () => {
  if (currentQuestion.value < questionList.value.length - 1) {
    currentQuestion.value++
    resetQuestionState()
  }else {
    // 已是最后一题，弹窗确认是否提交
    Taro.showModal({
      title: '提示',
      content: '您已完成全部题目，是否提交？',
      success: async (res) => {
        if (res.confirm) {
          await submitAllRecords()
          // Taro.reLaunch({ url: '/pages/index/index' }) // 跳转到首页
        }
      }
    })
  }
}
onUnmounted(() => {
  // 页面卸载前执行
  handleExit()
})
// 处理用户退出页面逻辑
const handleExit = async () => {
  await submitAllRecords()
  // Taro.reLaunch({ url: '/pages/index/index' }) // 强制跳转首页
}

const goToQuestion = (index) => {
  currentQuestion.value = index
  resetQuestionState()
}

const resetQuestionState = () => {
  showAnalysisContent.value = true
  isCorrect.value = null
  selectedOption.value = []
  updateQuestionData();
  isQuestionCollected(questionData.value.id);
}
</script>

<style lang="scss">

@use "../../components/common.scss";
</style>